// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DbHelper.cs" company="SmartPlan">
//   SmartPlan 2011
// </copyright>
// <summary>
//   The db helper.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace DbDiff.WinClient.Helper
{
    using System;
    using System.Collections.Specialized;
    using System.Data.SqlClient;
    using Common.Helper;
    using Common.Model;

    /// <summary>
    /// The db helper.
    /// </summary>
    public static class DbHelper
    {
        /// <summary>
        /// The get database list.
        /// </summary>
        /// <param name="server">
        /// The server.
        /// </param>
        /// <returns>
        /// The databases at sql server
        /// </returns>
        public static StringCollection GetDatabaseList(RegisteredServer server)
        {
            return GetDatabaseList(server.Name, server.AuthType, server.User, server.Password);
        }

        /// <summary>
        /// The get database list.
        /// </summary>
        /// <param name="server">
        /// The server.
        /// </param>
        /// <param name="authType">
        /// The auth type.
        /// </param>
        /// <param name="user">
        /// The user.
        /// </param>
        /// <param name="password">
        /// The password.
        /// </param>
        /// <returns>
        /// </returns>
        /// <exception cref="DbDiffClientException">
        /// </exception>
        public static StringCollection GetDatabaseList(string server, AuthType authType, string user, string password)
        {
            string connectString = DatabaseConnectString.GetConnectString(server, "master", user, password, authType);
            var databases = new StringCollection();
            const string ListCommandString = "select name from master.dbo.sysdatabases WHERE IsNull(HAS_DBACCESS (name),0)=1 order by name";

            try
            {
                using (var connection = new SqlConnection(connectString))
                {
                    var listCommand = new SqlCommand(ListCommandString, connection);
                    connection.Open();
                    using (SqlDataReader reader = listCommand.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            databases.Add(reader.GetString(0));
                        }

                        reader.Close();
                    }

                    connection.Close();
                }
            }
            catch (Exception e)
            {
                throw new DbDiffClientException("ERROR: Load database list", e);
            }

            return databases;
        }

    }
}
